package com.awccis.driver.controller;

import com.awccis.common.pool.CustomerPool;
import com.awccis.common.pool.DriverPool;
import com.awccis.common.utils.Constants;
import com.awccis.common.utils.TimeUtils;
import com.awccis.common.websocket.CustomerWsServer;
import com.awccis.customer.model.order.OrderBean;
import com.awccis.driver.model.DriverInfo;
import com.awccis.driver.model.NoFinishOrder;
import com.awccis.driver.model.StatusBean;
import com.awccis.driver.model.credit.CreditBean;
import com.awccis.driver.model.order.HistoryOrderBean;
import com.awccis.driver.service.DriverService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 纯牛奶丶
 * @Date: 2018-04-14 13:41
 * @Since: 1.0
 * @Description:
 **/
@Controller
@RequestMapping(value = "/driverOrder", method = RequestMethod.POST)
public class DriverOrderController {

    /**
     * 日志打印对象
     */
    private Logger logger = LoggerFactory.getLogger(DriverOrderController.class);

    @Resource
    DriverService driverService;

    /**
     * 查询司机当前订单信息
     *
     * @param driverInfo {"driverNickName": 28}
     * @return {"result": orderBean}
     */
    @RequestMapping(value = "/selectCurrentOrder", produces = "application/json; charset=UTF-8")
    public @ResponseBody
    Object selectCurrentOrder(@RequestBody DriverInfo driverInfo) {
        logger.info("司机当前订单信息：" + driverInfo.toString());
        Map<String, Object> map = new HashMap<>(2);

        OrderBean orderBean = driverService.selectCurrentOrder(driverInfo);
        if(orderBean==null ){
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "查询失败！");
        }else{
            map.put(Constants.MAP_KEY_RESULT, true);
            map.put(Constants.MAP_KEY_MESSAGE, orderBean);
        }
        return map;
    }

    /**
     * 给司机推送订单
     *
     * @return
     */
    @RequestMapping(value = "/getNoFinishOrders", produces = "application/json; charset=UTF-8")
    public @ResponseBody
    Object getNoFinishOrders(@RequestBody HashMap<String,Integer> requestMap) {
        Map map = new HashMap();
        if(requestMap.get("driverId")!=null){
            List<NoFinishOrder> list = driverService.getNoFinishOrders(requestMap.get("driverId"));
            if(list.size()==0){
                map.put(Constants.MAP_KEY_RESULT,false);
                map.put(Constants.MAP_KEY_MESSAGE,"没有未完成订单!");
            }else{
                map.put(Constants.MAP_KEY_RESULT,true);
                map.put(Constants.MAP_KEY_MESSAGE,list);
            }
        }else{
            map.put(Constants.MAP_KEY_RESULT,false);
            map.put(Constants.MAP_KEY_MESSAGE,"请求参数异常!");
        }
        return map;
    }

    /**
     * 更改订单的不同状态,
     * 首先判断司机driverId是否为空，driverId在司机登陆的时候已经返还给司机的页面端，
     *
     * @param orderBean {"driverId":1, "timeType":"receiveTime", "orderId":"1"}
     * @return {"result": "true"}
     */
    @RequestMapping(value = "/updateOrderStatus", produces = "application/json; charset=UTF-8")
    public @ResponseBody
    Object updateOrderStatus(@RequestBody OrderBean orderBean) {
        logger.info("根据不同状态下更改订单表：" + orderBean.toString());
        Map<String, Object> map = new HashMap<>(2);

        if (0 == orderBean.getDriverId()) {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, Constants.MAP_VALUE_ILLEGAL_REQUEST);
            return map;
        } else {
            boolean result = driverService.updateDifferOrderTime(orderBean);
            map.put(Constants.MAP_KEY_RESULT, result);

            int id = orderBean.getDriverId();
            String beginDate = "00:00:00";
            String endDate = "08:00:00";
            if (orderBean.getTimeType().equals(Constants.DRIVER_ORDER_RECEIVE_TIME)) {
                if(result){
                    DriverPool.updateIsWorkById(orderBean.getDriverId(),true);
                    double creditAction = 0.5;
                    String creditReason = "在一分钟内时间接单！";
                    driverService.insertDriverCredit(new CreditBean(id, creditAction, creditReason));
                }else{
                    DriverPool.updateIsWorkById(orderBean.getDriverId(),false);
                    map.put(Constants.MAP_KEY_MESSAGE,"乘客已取消订单!");
                    return map;
                }
                send(orderBean,"receive:ok!");
            }else if(orderBean.getTimeType().equals(Constants.DRIVER_ORDER_TRAVEL_ONTIME)){
                send(orderBean,"travelOn:ok!");
            }else if(orderBean.getTimeType().equals(Constants.DRIVER_ORDER_TRAVEL_END_TIME)){
                DriverPool.updateIsWorkById(orderBean.getDriverId(),false);
                double creditAction = 2;
                String creditReason = "司机点击行程到达！";
                if(TimeUtils.isInDate(new Date(), beginDate, endDate)){
                    creditAction *= creditAction;
                }
                driverService.insertDriverCredit(new CreditBean(id, creditAction, creditReason));
                send(orderBean,"travelEnd:ok!");
            }else if(orderBean.getTimeType().equals(Constants.DRIVER_ORDER_FINISH_TIME)){
                send(orderBean,"travelFinish:ok!");
            }
        }
        return map;
    }

    /**
     * 查询历史订单信息
     *
     * @param hashMap {"driverNickName": 23, "totalCount":-1, "startCount": 2, "limitCounts": 3}
     * @return {"result": true,"message": [{"orderFinishTime": 1523350958000,"orderTravelOnPlace": "南京科技","orderTravelEndPlace": "南京工业","totalCount": 0}],"totalCount": 8}
     */
    @RequestMapping(value = "/getHistoryOrders", produces = "application/json; charset=UTF-8")
    public @ResponseBody
    Object getHistoryOrders(@RequestBody HashMap<String, Object> hashMap) {
        logger.info("查询历史订单信息数据：" + hashMap.toString());
        Map<String, Object> map = new HashMap<>(2);
        List<HistoryOrderBean> list;

        String totalCount = "totalCount";
        int counts = Integer.parseInt(hashMap.get(totalCount).toString());
        int resultCount;
        //若传入的总数值不为-1则直接返回传入的值
        if (counts == -1) {
            resultCount = driverService.selectDriverOrderCount(hashMap);
        } else {
            resultCount = counts;
        }
        int driverNickName;
        try {
            driverNickName = Integer.parseInt(hashMap.get("driverNickName").toString());
        } catch (NumberFormatException e) {
            logger.warn("查看历史订单请求值非法：" + e);
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "非法请求值！");
            return map;
        }
        if (driverNickName != 0) {
//            //判断查询订单信息的账户是否是登陆状态，若不是，则不能查询
//            boolean b = DriverPool.isContainByNickname(driverNickName);
//            if (b) {
                list = driverService.selectHistoryOrders(hashMap);
                if (list.size() == 0) {
                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, "您当前还没有订单信息！");
                } else {
                    map.put(Constants.MAP_KEY_RESULT, true);
                    map.put(Constants.MAP_KEY_MESSAGE, list);
                    map.put(Constants.MAP_KEY_TOTAL_COUNT, resultCount);
                }
//            } else {
//                map.put(Constants.MAP_KEY_RESULT, false);
//                map.put(Constants.MAP_KEY_MESSAGE, Constants.MAP_VALUE_ILLEGAL_REQUEST);
//            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, Constants.MAP_VALUE_ILLEGAL_REQUEST);
        }
        return map;
    }



    /**
     * 消息推送方法
     * @param orderBean orderBean
     * @param msg msg
     */
    private void send(OrderBean orderBean,String msg){
        new Thread(new Runnable() {
            @Override
            public void run() {
                int count = 0;
                while (!CustomerPool.sendMessageByPhone(orderBean.getCustomerPhone(), msg)) {
                    try {
                        Thread.sleep(5000);
                        count++;
                        if (count >= 12) {
                            break;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                }
            }
        }).start();
    }
}
